import { ConfigEnv, defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import Components from 'unplugin-vue-components/vite'
import Pages from 'vite-plugin-pages'
import Unocss from 'unocss/vite'
import AutoImport from 'unplugin-auto-import/vite'
import { viteMockServe } from 'vite-plugin-mock'
const path = require('path')

// 0. 配置浏览器 document title
// 1. 配置打包文件名规范 -- rollupOptions
// 2. 超大资源拆分 -- manualChunks
// 3. 清除 console 和 debugger -- vite-plugin-compression

// https://vitejs.dev/config/
export default ({ command }: ConfigEnv) =>
  defineConfig({
    // base: 'chemical-collection',
    plugins: [
      vue({
        reactivityTransform: true,
      }),
      Unocss({
        /* options */
      }),
      Pages({
        dirs: 'src/views',
      }),
      vueJsx(),
      AutoImport({
        imports: ['vue', 'vue/macros', 'vue-router', '@vueuse/core'],
        dts: true,
        dirs: ['src/store/modules', 'src/service/api'],
      }),
      // ui库解析器，也可以自定义
      Components({
        // 指定组件位置，默认是src/components
        dirs: ['src/components/common'],
        // ui库解析器
        // resolvers: [ElementPlusResolver()],
        extensions: ['vue'],
        // 配置文件生成位置
        dts: 'components.d.ts',
      }),
      viteMockServe({
        mockPath: 'mock',
        localEnabled: command === 'serve',
        logger: true, // 是否在控制台显示请求日志
        supportTs: true, // 打开后，可以读取 ts 文件模块 打开后将无法监视 .js 文件
      }),
    ],
    resolve: {
      alias: {
        '~': path.resolve('./'),
        '@': path.resolve(__dirname, 'src'),
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            hack: `true; @import (reference) "${path.resolve('src/styles/theme.less')}";`,
          },
          javascriptEnabled: true,
        },
      },
    },
    server: {
      host: '127.0.0.1',
      port: 3000,
      open: true,
      proxy: {
        '/mock': {
          target: 'http://localhost:3333/mock/fetchData',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/mock/, ''), // 重写路径把路径变成空字符
        },
      },
    },
    build: {
      rollupOptions: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return id.toString().split('node_modules/')[1].split('/')[0].toString()
          }
        },
      },
    },
    // build: {
    //   // sourcemap: true,
    //   terserOptions: {
    //     compress: {
    //       drop_console:true,
    //       drop_debugger:true
    //     }
    //   }
    // }
  })
